/**
 * Author       :       Kang, JulKi
 * E-mail       :       jkkang65@@hanmail.net
 * 
 * Ver		:	1.32
 * 
 * Last updated 2011. 9. 07 
 * Copyleft () 2011, All rights is not reserved..
 */

import  java.awt.*;
import  java.awt.event.*;
import	java.awt.Color;
import  javax.swing.*;
import	javax.swing.event.*;
import  javax.swing.JSlider;
import	javax.swing.border.TitledBorder;

import	java.net.*;
import	java.io.*;

import	java.lang.*;
import	java.util.*;
import	java.util.Hashtable;
import	java.util.Enumeration;

class MySlider extends JSlider implements ChangeListener
{
	TitledBorder tb;
	
	public MySlider(int min, int max, int value)
	{
		super(min, max, value);
		
	        setMajorTickSpacing(5);
	        setMinorTickSpacing(1);
		setPaintTicks(true);
	        setPaintLabels(true);
	        
	        tb = new TitledBorder("Sleep : " + value + " (sec) ");
	        //setBorder(new TitledBorder("Sleep : " + value + " (sec)"));
	        tb.setTitleJustification(TitledBorder.RIGHT);
	        setBorder(tb);
	        
	        addChangeListener(this);

	        // slider.setBorder(new TitledBorder(str));
	}
	
	public void stateChanged(ChangeEvent e)
	{
		JSlider source = (JSlider)e.getSource();
		
		int value = (int)source.getValue();
		
		if (value == 0) {
			value = 1;
			this.setValue(value);
		}
		System.out.println("sleep : " + value);
		tb.setTitle("Sleep : " + value + " (sec) ");
	}
}

class MyFrame extends JFrame implements ActionListener, WindowListener
{
	ServerSocket	ss = null;
	Socket		sc;
	//InputStream	is;
	//OutputStream	os;
	int		iPortNum = 20111;
		
	JButton         yes_bt = new JButton("Ok");
        JButton         can_bt = new JButton("Cancel");
//        MySlider	slider = new MySlider(0, 10, 5);
        
        JButton[]	jGridButton; 

        JPanel          pGrid;
        JPanel          pMenu;

       //Dimension	gridD;
        Dimension       screen;
        Dimension       f_size;
        int		xPos, yPos;
        int		nSteps;
        byte[]		pBuf;
        
        Hashtable<String, String>	ht = new Hashtable<String, String>();

        public MyFrame ()
        {
                //d = new Dimension(x, y);
                screen = Toolkit.getDefaultToolkit().getScreenSize();

                socketInit();	// Socket startup                
                eventAdd();        // Event add or Thread add

                //setResizable(false);
                //this.setVisible(true);

                //super.pack();
        }
        
         public void drawFrame()
         {
                this.setSize(600, 600);
                this.setTitle("Hello, My JFrame : " + getGridX() + "x" + getGridY() + "  Step (" + getNSteps() + ")");

                Container cp = this.getContentPane();

                cp.setBackground(new Color(Color.white.getRGB()));
                cp.setLayout(new BorderLayout());
                  
                cp.add((pGrid = new JPanel()), BorderLayout.CENTER);
                cp.add((pMenu = new JPanel()), BorderLayout.SOUTH);
                //pMenu = new JPanel();
                //pMenu.setPreferredSize(new Dimension(150, 30));
                //cp.add(pMenu, BorderLayout.SOUTH);
        
                pGrid.setLayout(new GridLayout(getGridX(), getGridY()));
        
                pMenu.setLayout(new GridLayout(1, 3));
                pMenu.add(yes_bt);
                pMenu.add(can_bt);
                 pMenu.add(new MySlider(0, 10, 5));

                jGridButton = new JButton[getGridX() * getGridY()];
                
        	//System.out.println("gridD.getWidth() = " + (int)gridD.getWidth() + " gridD.getHeight() = " + (int)gridD.getHeight());
        	
        	for (int i=0; i<getGridXY(); i++) {
                	//System.out.println("i. = " + Integer.toString(i));

                	jGridButton[i] = new JButton();
                	pGrid.add(jGridButton[i]);
        
//        		for (int i=0; i<str.length(); i++) {
//        			num = bs[i] - 48;
//  	  			System.out.println("bs[" + i + "] = " + num);
//        		}	

                	jGridButton[i].setBackground(new Color(255, 0, 0));
                	//if (pBuf[i]-48 == 0)	jGridButton[i].setBackground(new Color(Color.lightGray.getRGB()));
                	//else			jGridButton[i].setBackground(new Color(Color.darkGray.getRGB()));
                }
             
        	f_size = this.getSize();

                this.xPos = (int)(screen.getWidth() / 2 - f_size.getWidth() / 2);
                this.yPos = (int)(screen.getHeight() / 2 - f_size.getHeight() / 2);
                
                setLocation(this.xPos, this.yPos);
                //setResizable(false);
		setVisible(true);
		//super.pack();
        }
        
        public void changeButtonColor(int step)
        {
        	this.setTitle("Hello, My JFrame : " + getGridX() + "x" + getGridY() + "  Step (" + step + "/" + getNSteps() + ")");
                
        	//System.out.println("gridSize = " + gridSize);
        	
        	for (int i=0; i<getGridXY(); i++) {
                	if (pBuf[i]-48 == 0)	jGridButton[i].setBackground(new Color(Color.lightGray.getRGB()));
                	else			jGridButton[i].setBackground(new Color(Color.darkGray.getRGB()));
                }
        }
        
        public void eventAdd()
        {
                this.addWindowListener(this);
                yes_bt.addActionListener(this);
                can_bt.addActionListener(this);
        }

        public void socketInit()
        {
        	//byte[]		bNStep_size = new byte[10];
        	//byte[]		bGridX_size = new byte[10];
        	//byte[]		bGridY_size = new byte[10];
        	//int		iGridX_size, iGridY_size;
        	int		step = 1;
        	boolean		isFirst = true;
        	String		msg;

       		try {
       				//boolean flag = true;
       			//Hashtable<String, String>	ht = new Hashtable<String, String>();
       			//Hashtable	ht = new Hashtable();
       			Enumeration	en;
       			//StringTokenizer	st;
       			
       			ss = new ServerSocket(iPortNum);
        		
       			System.out.println("Server with Port(" + iPortNum + ") is ready...");
       			System.out.println("Connection waiting...");

			sc = ss.accept();
			System.out.println(sc.getInetAddress() + " connected...");
			
			//is = sc.getInputStream();
			
			BufferedReader br = new BufferedReader(new InputStreamReader(sc.getInputStream()));

			/*
			 * get stream data from socket
			 */
			while ((msg = br.readLine()) != null) {
				String[] parsing = msg.split(" ");
				System.out.print("parsing[0] = " + parsing[0] + " ");
				System.out.println("parsing[1] = " + parsing[1] + " ");
				//System.out.println("isFirst = " + isFirst);
												
				if (parsing[0].equals("nsteps") || parsing[0].equals("grid_x") || parsing[0].equals("grid_y")) {
					// save key & value at the hash table
					ht.put(parsing[0], parsing[1]);
					
					//if (ht.containsKey("grid_x") && ht.containsKey("grid_y")) {
						// = new Dimension(getGridX(), getGridY());
			        		
						//System.out.println("gridD.Width = " + (int)gridD.getWidth());
						//System.out.println("gridD.Height = " + (int)gridD.getHeight());	
					//}
				}
				
				if (parsing[0].equals("grid_data")) {
					if (isFirst == true) {
						//System.out.println("drawFrame");
						drawFrame();
						//pBuf = parsing[1].getBytes();
						isFirst = false;
					}

					pBuf = parsing[1].getBytes();
		       			/*
		       			for (int i=0; i<parsing[1].length(); i++) {
		       	        		int num = pBuf[i] - 48;
		       	        		System.out.println("pBuf[" + i + "] = " + num);
		       	        	}
		       				
		       			System.exit(0);
		       	        	*/
					//System.out.println("changeButtonColor");
					changeButtonColor(step);
					step++;
				}
				/*try {
					Thread.sleep(100000);
				} catch (InterruptedException e) {}
				*/
				//System.exit(0);
			}

			//System.out.println("nsteps : " + getNSteps());
			//System.out.println("grid_x : " + getGridX());
			//System.out.println("grid_y : " + getGridY());
			br.close();
			sc.close();
			ss.close();

			//System.out.println("is.close(), sc.close(), ss.close()");
			
			System.out.println("");
			System.out.println("This job is successfully finished...");
       		}
       		catch  (IOException e) {
       			e.printStackTrace();
       		}
        }
        
        public int getNSteps()
        {
        	
        	return Integer.parseInt((String)ht.get("nsteps"));
        }
        
        public int getGridX()
        {
        	return Integer.parseInt((String)ht.get("grid_x"));
        }
        
        public int getGridY()
        {
        	return Integer.parseInt((String)ht.get("grid_y"));
        }

        public int getGridXY()
        {
        	return	getGridX() * getGridY();
        }
        
        public void actionPerformed(ActionEvent e)
        {
                if (e.getSource() == yes_bt)
                {
                        System.out.println("Ok button pressed...");
                }
                else if (e.getSource() == can_bt)
                {
                        System.out.println("Exit button pressed...");
                }
        }

        public void windowClosing(WindowEvent e)
        {
                System.out.println("System control button pressed to exit...");
                System.exit(0);
        }
        
        public void windowClosed(WindowEvent e) {}
        public void windowOpened(WindowEvent e) {}
        public void windowActivated(WindowEvent e) {}
        public void windowDeactivated(WindowEvent e) {}
        public void windowIconified(WindowEvent e) {}
        public void windowDeiconified(WindowEvent e) {}
}

/**
 * 
 * @@author jkkang
 *
 * start of Main()
 */
public class MyFrameMain
{
        public static void main(String [] args)
        {
                MyFrame myFrame = new MyFrame();
        }
}
